package com.unism.licence;

import java.io.FileInputStream;
import java.net.URL;
//import org.apache.log4j.Logger;
import org.jdom2.*;

import com.unism.licence.xml.*;
import com.unism.licence.key.*;
import java.security.interfaces.RSAPublicKey;

public class CheckLicence {

	private String projectName ;
	private int clientsNum ;
	private long issueDt ;
	private long validLife ;

	
	/**
	 * licence验证
	 */
	public boolean doCheck(URL licenceFilePath) {
		if(licenceFilePath == null){
			return false ;
		}
		ReadLicenceXmlFile reader = new ReadLicenceXmlFile(licenceFilePath);
		FileInputStream in = reader.getLicenceFileIn();
		if (in == null) {
			return false ;
		} else {
			boolean flag = this.checkLicence(in);
			reader.closeLicenceFileIn(in);
			return flag ;
		}
	}
	
	/**
	 * licence生命周期是否有效
	 * @return
	 */
	public boolean isValidLife(){
		long now = System.currentTimeMillis() ;
		if(now - issueDt > validLife){
			//过期了
			return false ;
		}else{
			//有效期内
			return true ;
		}
	}

	/**
	 *
	 */
	private boolean checkLicence(FileInputStream in) {
		/////////////////////////////////////////////
		//分析licence文件
		ParseLicenceXmlFile parse = new ParseLicenceXmlFile();
		Document doc = parse.createDom(in);
		if (doc == null) {
			return false ;
		}
		if(!parse.parseXml()){
			return false ;
		}
		
		this.projectName = parse.getProjectName();
		String macTxt = parse.getMacTxt();
		String clientsTxt = parse.getClientsTxt();
		String issueDtTxt = parse.getIssueDtTxt() ;
		String validLifeTxt = parse.getValidLifeTxt() ;
		String exponentHex = parse.getExponentHex() ;
		String modulusHex = parse.getModulusHex() ;
		String signedTxt = parse.getSignedTxt() ;

		
		try {
			this.clientsNum = Integer.parseInt(clientsTxt);
			this.issueDt = Long.parseLong(issueDtTxt);
			this.validLife = Long.parseLong(validLifeTxt);
		} catch (Exception e) {
			return false ;
		}


		/////////////////////////////////////////
		//验证licence
		Verification vy = new Verification();
		/////////////////////////////////////////
		//验证id
		if(vy.isWanYongMac(macTxt)){
			this.clientsNum = 2 ;
		}else{
			if (!vy.checkMac(macTxt)) {
				return false ;
			}
		}
		
		/////////////////////////////////////////
		//生成公钥
		Key key = new Key();
		RSAPublicKey publicKey = key.generateRSAPublicKey(exponentHex, modulusHex);
		if (publicKey == null) {
			return false ;
		}

		/////////////////////////////////////////
		//验证签名
		boolean flag = vy.checkSignedValue(macTxt, this.clientsNum, this.issueDt, this.validLife, publicKey, signedTxt);
		if (flag == false) {
			return false ;
		}
  		return true ;
 	}

	public String getProjectName(){
		return this.projectName ;
	}
	
	public int getClientsNum() {
		return this.clientsNum ;
	}

	public long getIssueDt() {
		return issueDt;
	}

	public long getValidLife() {
		return validLife;
	}


}
